package article

import (
	"gin-project-01/gin-step04/gin18-trans/controllers"
	myModel "gin-project-01/gin-step04/gin18-trans/models"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
)

type BankController struct {
	controllers.BaseController //继承 controllers.BaseController
}

// Index
//
//	@Description:
//	@receiver a
//	@param c
func (a BankController) Index(c *gin.Context) {
	var bankList []myModel.Bank
	myModel.Db.Find(&bankList)
	c.JSON(http.StatusOK, bankList)

}

// Trans
//
//	@Description: 转账 增加事务操作
//	@receiver a
//	@param c
func (a BankController) Trans(c *gin.Context) {
	var trans float64 = 5
	//开启事务！ 后续使用tx
	tx := myModel.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			msg, ok := r.(string)
			if !ok {
				msg = "转账失败"
			}
			c.JSON(http.StatusOK, myModel.Fail(msg+",执行回滚"))
		} else {
			tx.Commit()
			a.Index(c)
		}
	}()

	var zs myModel.Bank
	tx.Where("id = ?", 1).Find(&zs)
	if zs.Balance < trans {
		panic("余额不足")
	}
	zs.Balance -= trans
	tx.Save(&zs)

	//模拟异常~
	num := rand.Intn(10)
	if num%3 == 0 {
		panic("转账过程异常~")
	}

	var lisi myModel.Bank
	tx.Where("id = ?", 2).Find(&lisi)
	lisi.Balance += trans
	tx.Save(&lisi)

}
